<script setup>
import { ref } from 'vue'
import { onMounted } from 'vue';
import { userStore } from '../../stores/userStore.js'
import api from '../../api/api.js'
import { ElMessage } from 'element-plus'
// 代码块高亮
import hljs from 'highlight.js'
import 'highlight.js/styles/atom-one-dark.css'
window.hljs = hljs

const userInfo = userStore()
const { nickname } = userInfo;

// 数据定义
// 文章标题
const articleTitle = ref('')
// 文章作者
const articleAuthor = ref('管理员')
// 文章内容
const articleContent = ref(null)
//文章图片列表
const articleImgList = ref([])
//当前编辑的文章id
const articleId = ref(0)



//文章内容更新函数
function updateHTML(html) {
	//保存文章内容到变量中
	articleContent.value = html
}

//获取当前编辑文章的id
const getArticleId = async () => {
	try {
		const res = await api.getNewArticleIdApi({ uid: userInfo.userid })
		articleId.value = res.data.aid;
	} catch (error) {
		console.error(error)
	}
}


//提交文章内容
const submitArticle = async () => {
	try {
		if (!articleTitle.value || !articleContent.value) {
			ElMessage.warning('标题和内容不能为空')
			return;
		}
		const res = await api.commitArticleApi({
			aid: articleId.value,
			articleTitle: articleTitle.value,
			uid: userInfo.userid,
			name: articleAuthor.value,
			content: articleContent.value,
			tid: 2,
			imgList: articleImgList.value
		})
		if (res.code === 200) {
			ElMessage.success('发布成功')
			// 重置文章内容
			articleTitle.value = ''
			articleContent.value = ''
			editorArticle.root.innerHTML = ''
			articleImgList.value = []
		}
	} catch (error) {
		console.error(error)
	}
}

// 富文本编辑器
let editorArticle


// 富文本编辑器配置
const TOOLBAR_CONFIG = [
	['undo', 'redo', 'clean'],
	[{ header: [1, 2, 3, false] }, { color: [] }, 'bold', 'italic', 'strike', 'underline'],
	[{ list: 'ordered' }, { list: 'bullet' },],
	['link', 'blockquote', 'code', 'code-block', 'image'],
	['fullscreen'],
]

// 富文本编辑器初始化
onMounted(async () => {
	// ssr compat, reference: https://vitepress.dev/guide/ssr-compat#importing-in-mounted-hook
	import('@opentiny/fluent-editor').then((module) => {
		const FluentEditor = module.default

		editorArticle = new FluentEditor('#editorArticle', {
			theme: 'snow',
			modules: {
				toolbar: TOOLBAR_CONFIG,
				syntax: true,
			},
			uploadOption: {
				imageUpload: ({ file, callback }) => {
					imageHandler(file, (imageUrl) => {
						// 调用 callback，传入 imageUrl 即可实现图片渲染
						callback({
							code: 0,
							message: 'Upload success!',
							data: {
								imageUrl,
							},
						})
					})
				},
			},
		})
		updateHTML(editorArticle.root.innerHTML)

		editorArticle.on('text-change', () => {
			updateHTML(editorArticle.root.innerHTML)
		})
	})

	//文章作者信息初始化
	articleAuthor.value = nickname;
	//获取文章id
	await getArticleId();

})

// 图片上传================
/**
 * 上传图片到服务器
 * @param image File 格式的图片
 * @param callback 回调函数，用来处理服务器返回的图片 URL
 * 除了 XMLHttpRequest，也可以使用 fetch / axios 等工具实现图片上传。
 */
async function imageHandler(image, callback) {
	const data = new FormData()
	data.append('file', image)
	data.append('aid', articleId.value)
	try {
		console.log("文章id", articleId.value)
		// const response = await axios.post(IMG_API_URL, data);
		const response = await api.uploadImgApi(data);

		// 图片上传成功，就直接返回图片 URL
		callback(response.data.purl)

		const pid = response.data.pid;
		const purl = response.data.purl;
		const aid = articleId.value;
		const uid = userInfo.userid;
		articleImgList.value.push({ pid, purl, uid, aid })

	} catch (error) {
		console.error(error)
		// 图片上传失败了，就转成 Base64 格式
		const reader = new FileReader()
		reader.onload = function (e) {
			callback(e.target.result)
		}
		reader.readAsDataURL(image)

	}
}
</script>


<template>
	<div class="container">
		<div class="box">
			<div class="title-bar">
				<h3>发布公告</h3>
				<el-button type="primary" @click="submitArticle">确认发布</el-button>
				<p>标题</p>
				<el-input v-model="articleTitle" ></el-input>
				<p>内容</p>

			</div>

			<div id="editorArticle">

			</div>

		</div>
	</div>
</template>


<style scoped lang="less">
.container {
	margin: 0;
	padding: 0;
	width: 100%;
	height: 100%;
	background-color: #f5f5f5;
	display: flex;
	align-items: center;

	.box {
		width: 95%;
		margin: 0 auto;
		height: 85vh;
		overflow: auto;
		background-color: #fffbf6;
		padding: 15px;

		.title-bar {
			width: 50%;
		}
	}
}
</style>